package com.imdroid.carac.activities;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.Tts;
import com.imdroid.carac.model.Destination;
import com.imdroid.carac.net.HttpHelper;
import com.imdroid.carac.net.Weibo;
import com.imdroid.carac.process.ProcessFactory;
import com.imdroid.carac.process.UserProcess;
import com.imdroid.carac.services.SoundDetectService;
import com.imdroid.carac.speechRecog.SpeechRecog;

/**
 * The home menu activity
 * 
 */
public class HomeActivity extends BaseActivity {

	private static HomeActivity instance;

	public static HomeActivity getInstance() {
		return instance;
	}

	/**
	 * The tag of the activity
	 */
	private final static String TAG = "HomeActivity";
	/**
	 * 进度条常量
	 */
	private ProgressBar mProgress;
	/**
	 * 中断下载变量
	 */
	private boolean interceptFlag = false;
	/**
	 * 下载对话框
	 */
	private Dialog alertDialog;
	/**
	 * 下载对话框
	 */
	private Dialog downloadDialog;
	/**
	 * 下载文件
	 */
	String saveFileName = "IMDroid-Client.apk";
	// 最后提示更新时间
	private long lastUpdateRemind = 0;

	private View homeBg;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		homeBg = findViewById(R.id.home_bg);
		allowBack = false;
		instance = this;

		// 注册定位服务

		// TextView textView = (TextView) this.findViewById(R.id.home_title);
		// try {
		// textView.setText(this.getString(R.string.title_home) + " "
		// + IMDroid.getAppVersion());
		// } catch (NameNotFoundException e) {
		// e.printStackTrace();
		// }

		if (IMDroid.getRecordBackground())
			FloatView.show();
		// 启动时登微博
		Weibo.toAuth = true;
		registerListenersForSpeechRecognition();
		// 启动自动路口自动亮屏幕的服务
		Intent in = new Intent(this, SoundDetectService.class);
		startService(in);
		// 检查是否有更换SIM卡
		TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String subscriberId = mTelephonyMgr.getSubscriberId();

		// 如果没有SIM卡
		if (subscriberId == null || subscriberId.length() <= 0) {
			AlertDialog.Builder builder = new Builder(this);
			builder.setTitle(R.string.app_name_main);
			builder.setMessage(R.string.home_no_sim);

			builder.setNegativeButton(R.string.home_okay,
					new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();
		} else {
			String lastSIMSubscriberId = IMDroid.getLastSIMSubscriberId();
			final View settingView = this.findViewById(R.id.home_setting);
			String sim_number = IMDroid.getUser().getSim_number();
			boolean no_sim_number = (sim_number == null || sim_number.trim().length() <= 0);
			boolean sim_number_change = (lastSIMSubscriberId != null
					&& lastSIMSubscriberId.length() > 0 && !subscriberId
					.equals(lastSIMSubscriberId));
			// 如果SIM卡已更换
			if (sim_number_change || no_sim_number) {
				AlertDialog.Builder builder = new Builder(this);
				builder.setTitle(R.string.app_name_main);
				builder.setMessage(no_sim_number ? R.string.home_no_sim_number
						: R.string.home_sim_number_input);

				builder.setNegativeButton(R.string.home_next_time,
						new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.setPositiveButton(R.string.home_config,
						new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								onSetting(settingView);
							}
						});
				builder.create().show();
			}
			IMDroid.setLastSIMSubscriberId(lastSIMSubscriberId);
		}

	}

	public void refreshNavigationIcon() {
		messageHandler.post(new Runnable() {
			public void run() {
				// 参考 refreshNotification() 方法
				// ((Button) findViewById(R.id.home_navigation))
				// .setBackgroundDrawable(getResources().getDrawable(
				// R.drawable.home_navi_point));
				findViewById(R.id.red_ball).setVisibility(View.VISIBLE);
			}
		});
	}

	private void registerListenersForSpeechRecognition() {
		findViewById(R.id.home_team).setOnKeyListener(okl);
		findViewById(R.id.home_team).setOnLongClickListener(olcl);
		findViewById(R.id.home_security).setOnKeyListener(okl);
		findViewById(R.id.home_security).setOnLongClickListener(olcl);
		findViewById(R.id.home_setting).setOnKeyListener(okl);
		findViewById(R.id.home_setting).setOnLongClickListener(olcl);
		findViewById(R.id.home_recog).setOnKeyListener(okl);
		findViewById(R.id.home_recog).setOnLongClickListener(olcl);
		findViewById(R.id.home_record).setOnKeyListener(okl);
		findViewById(R.id.home_record).setOnLongClickListener(olcl);
		findViewById(R.id.home_navigation).setOnKeyListener(okl);
		findViewById(R.id.home_navigation).setOnLongClickListener(olcl);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.carac.activities.BaseActivity#onKeyDown(int,
	 * android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_ENTER) {
			SpeechRecog.go();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onStop() {
		super.onStop();
		// if (homeBg != null) {
		// ((AnimationDrawable) homeBg.getBackground()).stop();
		// }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.carac.activities.BaseActivity#onResume()
	 */
	protected void onResume() {
		super.onResume();
		if (homeBg != null) {
			// ((AnimationDrawable)homeBg.getBackground()).start();
		}
		refreshNotification();

		// 尝试连接服务器
		(new PingTask()).execute();

		// 检查是否有新版本
		if ((new Date()).getTime() - lastUpdateRemind > 24 * 60 * 60 * 1000)
			(new CheckNewVersionTask()).execute(new Object());

		// 更新welcome text
		TextView tv = (TextView) this.findViewById(R.id.home_welcome_text);
		tv.setText(getWelcomeText());

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	protected void onDestroy() {
		super.onDestroy();
		// 整个程序退出时，停止录像，清除悬浮窗
		// FloatView.finish();
		// Record.stop();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("回桌面");
		return super.onCreateOptionsMenu(menu);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent in = new Intent(Intent.ACTION_MAIN, null);
		in.addCategory(Intent.CATEGORY_HOME);
		startActivity(in);
		return super.onMenuItemSelected(featureId, item);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER) {
			startSpeechRecognitionAction();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	// 打开安保
	public void onSecurity(View view) {
		// Toast.makeText(this, "aaa", Toast.LENGTH_SHORT).show();
		startActivity(new Intent(this, SecurityStartupActivity.class));
		// IMDroid.antiTheft();
	}

	// 打开设置
	public void onSetting(View view) {
		startActivity(new Intent(this, OptionsActivity.class));
	}

	/**
	 * Take the photo
	 */
	public void takePhoto(int cameraId) {
		Camera camera = Camera.open();
		Parameters parameters = camera.getParameters();
		parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
		parameters.setSceneMode(Parameters.SCENE_MODE_AUTO);
		parameters.setAntibanding(Parameters.ANTIBANDING_AUTO);
		parameters.setWhiteBalance(Parameters.WHITE_BALANCE_AUTO);
		camera.startPreview();
		camera.takePicture(null, null, null, new JpegPictureCallback());
	}

	/**
	 * The inner class for saving the jpeg file which the camera took
	 * 
	 */
	private final class JpegPictureCallback implements PictureCallback {
		public void onPictureTaken(final byte[] jpegData,
				final android.hardware.Camera camera) {
			new Thread() {
				public void run() {
					try {
						Log.d(TAG, "Picture taken----" + jpegData.length);

						if (jpegData != null) {
							Bitmap bitmap = BitmapFactory.decodeByteArray(
									jpegData, 0, jpegData.length);

							File captureFile = new File(IMDroid.SECURITY_FOLDER
									+ (new Date()).getTime() + ".jpg");

							BufferedOutputStream bos = new BufferedOutputStream(
									new FileOutputStream(captureFile));
							bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
									bos);
							bos.flush();
							bos.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (camera != null) {
							camera.stopPreview();
							camera.release();
						}
					}
				}
			}.start();

		}
	}

	public void onRecog(View view) {
		SpeechRecog.go();
	}

	public void onTest(View view) {
		Tts.speak("张三 距离 ");
		Tts.speakDistance(1234.5678);
		Tts.speak(" 到 目地地址");

		// // new Thread() { public void run() {
		// try {
		// // Weixin.send( "/sdcard/a.jpg" );
		// Weixin.test();
		// } catch (Exception e) {
		// Toast.makeText(IMDroid.getContext(), "发微信失败："+e.getMessage(),
		// Toast.LENGTH_LONG).show();
		// Log.e("发微信失败：", ""+e);
		// }
		// // } }.start();
	}

	// 打开导航
	public void onNavi(View view) {
		// 如果没有目的地
		if (!IMDroid.hasDestination()) {
			// startActivity(new Intent(this, NavigatorPoints.class));
			startActivity(new Intent(this, NavigatorPointSetting.class));
		} else {
			// 如果接收到目的地
			final Destination d = IMDroid.getDestination();
			String message = this.getString(R.string.loc_cofirm_navi_address)
					+ d.getAddress();
			new AlertDialog.Builder(this)
					.setTitle(R.string.loc_message)
					.setMessage(message)
					.setPositiveButton(this.getString(R.string.loc_okay),
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Log.d(TAG, "d---" + d);
									navi(d);
								}
							})
					.setNegativeButton(this.getString(R.string.loc_cancel),
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									refreshNotification();
								}
							}).show();

			// navi(d);
		}
	}

	// 打开组队功能
	public void onTeam(View view) {
		startActivity(new Intent(this, TeamSelectActivity.class));
	}

	// 打开行车记录
	public void onRecord(View view) {
		startActivity(new Intent(this, RecordMenuActivity.class));
	}

	/**
	 * Show the check dialog
	 */
	private void showCheckDialog() {
		// 从服务器上检查是否有新版本下载
		lastUpdateRemind = (new Date()).getTime();
		AlertDialog.Builder builder = new Builder(this);

		builder.setTitle(R.string.home_version_title);
		builder.setMessage(R.string.home_version);

		builder.setPositiveButton("Ok", new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton("Cancel", new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
			}
		});
		alertDialog = builder.create();
		alertDialog.show();
	}

	/**
	 * Show the download dialog
	 */
	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(R.string.home_version_title);
		builder.setMessage(R.string.home_version_upgrade);

		final LayoutInflater inflater = LayoutInflater.from(this);
		View v = inflater.inflate(R.layout.home_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.home_progress);

		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();

		(new DownloadNewApkTask()).execute(mProgress);
	}

	/**
	 * Install the apk file
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(IMDroid.APP_FOLDER + "/" + saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		this.startActivity(i);
	}

	/**
	 * Refresh the information
	 */
	private void refreshNotification() {
		// 判断是否有目的地
		// String text = (String) this.getText(R.string.text_home_nv);
		// if (IMDroid.hasDestination()) {
		// text += "(*)";
		// ((Button) findViewById(R.id.home_navigation))
		// .setBackgroundDrawable(this.getResources().getDrawable(
		// R.drawable.home_navi_point));
		// // ((Button) findViewById(R.id.home_navigation)).setText(text);
		// } else {
		// ((Button) findViewById(R.id.home_navigation))
		// .setBackgroundDrawable(this.getResources().getDrawable(
		// R.drawable.home_navi));
		// }
		if (IMDroid.hasDestination()) {
			findViewById(R.id.red_ball).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.red_ball).setVisibility(View.GONE);
		}
	}

	/**
	 * welcome text
	 * 
	 * @return the welcome text
	 */
	private String getWelcomeText() {
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		String welcomeText;
		if (hour < 6)
			welcomeText = this.getString(R.string.home_welcome_text_e);
		else if (hour < 12)
			welcomeText = this.getString(R.string.home_welcome_text_m);
		else if (hour < 14)
			welcomeText = this.getString(R.string.home_welcome_text_a);
		else if (hour < 18)
			welcomeText = this.getString(R.string.home_welcome_text_n);
		else
			welcomeText = this.getString(R.string.home_welcome_text_e);
		return welcomeText.replace("%1%", IMDroid.getUser().getNickname());
	}

	/**
	 * 同步联系人
	 */
	public void syncContacts() {
		new Thread() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see java.lang.Thread#run()
			 */
			public void run() {
				Log.d("TAG", "Start to sync....");
				UserProcess p = (UserProcess) ProcessFactory
						.getProcess(UserProcess.class);
				try {
					IMDroid.setContactLastSync(new Date());
					p.synchronizeContact(IMDroid.getContext());
					// IMDroid.setContactLastSync(new Date());
				} catch (Exception e) {
					Log.d("TAG", e.getMessage());
					e.printStackTrace();
				}
			}

		}.start();
	}

	private void startSpeechRecognitionAction() {
		SpeechRecog.go();
	}

	private OnKeyListener okl = new OnKeyListener() {
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_ENTER && event.isLongPress()) {
				startSpeechRecognitionAction();
				return true;
			}
			return false;
		}
	};

	private OnLongClickListener olcl = new OnLongClickListener() {
		@Override
		public boolean onLongClick(View v) {
			return true;
		}
	};

	/**
	 * The async task to send the address
	 * 
	 */
	private class CheckNewVersionTask extends AsyncTask<Object, Void, Boolean> {
		// String url;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Boolean doInBackground(Object... params) {
			String clientVersion;
			try {
				clientVersion = IMDroid.getAppVersion();
				UserProcess process = (UserProcess) ProcessFactory
						.getProcess(UserProcess.class);
				String serverVersion = process.getLastVersion();
				// url =
				// HttpHelper.getShortenURL("http://whzb012945.chinaw3.com/webapp/GetUserPath?deviceId=317&day=5");
				return !serverVersion.startsWith(clientVersion);
			} catch (Exception e) {
				e.printStackTrace();
				Log.d(TAG, "Error in Checking New version." + e.getMessage());
				return false;
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// Log.d(TAG, "Shorten url--->" + url);
			// 如果有版本更新
			if (result) {
				showCheckDialog();
			}
		}
	}

	/**
	 * The async task of download
	 * 
	 */
	private class DownloadNewApkTask extends
			AsyncTask<ProgressBar, Integer, Boolean> {
		private ProgressBar bar;
		/**
		 * The apk file url
		 */
		private String apkUrl = HttpHelper.webAddress
				+ "resource/client/IMDroid-Client.apk?timeId="
				+ (new Date()).getTime();

		private int fileSize = 0;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Boolean doInBackground(ProgressBar... params) {
			try {
				bar = params[0];
				// 如果文件存在，则删除
				File apkFile = new File(IMDroid.APP_FOLDER + "/" + saveFileName);
				if (apkFile.exists())
					apkFile.delete();

				// 打开HTTP连接
				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				fileSize = conn.getContentLength();
				InputStream is = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(apkFile);

				int count = 0;
				byte buf[] = new byte[1024];
				do {
					int numread = is.read(buf);
					count += numread;

					if (numread <= 0) {
						break;
					}
					fos.write(buf, 0, numread);
					this.publishProgress(count);

				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
				return !interceptFlag;
			} catch (Exception e) {
				return false;
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			// 下载完成通知安装
			if (result) {
				downloadDialog.dismiss();
				installApk();
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		protected void onProgressUpdate(Integer... values) {
			// 更新进度
			int precentage = (int) (((float) values[0] / fileSize) * 100);
			Log.d(TAG, "-->" + values[0] + "/" + fileSize + "/" + precentage);
			bar.setProgress(precentage);
		}
	}

	/**
	 * The async task to ping the server
	 * 
	 */
	private class PingTask extends AsyncTask<Void, Void, Boolean> {
		// String url;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Boolean doInBackground(Void... params) {
			UserProcess process = (UserProcess) ProcessFactory
					.getProcess(UserProcess.class);
			return process.ping();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			TextView tv = (TextView) HomeActivity.this
					.findViewById(R.id.home_network_not_oka);
			tv.setVisibility(result ? View.INVISIBLE : View.VISIBLE);
		}
	}

	/**
	 * Sending the address
	 * 
	 * @param destination
	 *            the destination to be send
	 */
	private void navi(Destination destination) {
		BDLocation currentLocation = IMDroid.getCurrentLocation();
		if (currentLocation == null) {
			Toast.makeText(this,
					this.getString(R.string.loc_error_no_gps_wait),
					Toast.LENGTH_LONG).show();
			return;
		}
		double mLat1 = currentLocation.getLatitude();
		double mLon1 = currentLocation.getLongitude();
		double mLat2 = destination.getLatitude();
		double mLon2 = destination.getLongitude();
		int lat = (int) (mLat1 * 1E6);
		int lon = (int) (mLon1 * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (mLat2 * 1E6);
		lon = (int) (mLon2 * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);

		NaviPara para = new NaviPara();
		para.startPoint = pt1; // 起点坐标
		para.startName = this.getString(R.string.loc_map_loc);
		para.endPoint = pt2; // 终点坐标
		para.endName = destination.getAddress();
		System.out.println(mLat1 + " " + mLat2);

		try {
			BaiduMapNavigation.openBaiduMapNavi(para, this);
		} catch (BaiduMapAppNotSupportNaviException e) {
			// 在此处理异常
			e.printStackTrace();
		}
	}

}
